package com.lujianfei.powersearch

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.lujianfei.powersearch.base.BaseActivity
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.databinding.ActivityMainBinding
import com.lujianfei.powersearch.timer.GlobalTimerManager
import com.lujianfei.powersearch.ui.MainActivityViewModel
import com.lujianfei.powersearch.ui.about.AboutActivity
import com.lujianfei.powersearch.ui.createOrUpdate.CreateOrUpdateActivity
import com.lujianfei.powersearch.ui.report.TotalConsumeReportActivity
import com.lujianfei.powersearch.ui.search.SearchActivity
import com.lujianfei.powersearch.ui.select.SelectNodeActivity
import com.lujianfei.powersearch.ui.sort.SortItemActivity
import com.lujianfei.powersearch.ui.subitem.SubItemActivity
import com.lujianfei.powersearch.ui.test.TestActivity
import com.lujianfei.powersearch.utils.AppJumpUtils
import com.lujianfei.powersearch.utils.Constant
import com.lujianfei.powersearch.utils.SystemUtils
import com.lujianfei.powersearch.utils.ToastUtils

class MainActivity : BaseActivity<ActivityMainBinding>() {

    private val mMainActivityViewModel: MainActivityViewModel by lazy { buildViewModel() }
    override fun resourceId() = R.layout.activity_main

    override fun initView() {
        binding?.vm = mMainActivityViewModel
        setTitleMiddleText(getString(R.string.main_title), true)
        checkManagerPermission()
    }

    override fun initData() {
    }

    override fun initEvent() {
        mMainActivityViewModel.onItemClickCallback = { item ->
            SubItemActivity.jumpSubItemActivity(this@MainActivity, item)
        }
        mMainActivityViewModel.onItemLongClickCallback = { model ->
            val items = arrayOf("复制", "编辑", if (model.sort > 100L) "取消置顶" else "置顶","生成报表", "移动","取消")
            AlertDialog.Builder(this@MainActivity).setTitle("提示").setItems(items) { dialog, which ->
                dialog.dismiss()
                val item = items[which]
                if ("复制".equals(item, ignoreCase = true)) {
                    SystemUtils.copy(model.name)
                } else if ("编辑".equals(item, ignoreCase = true)) {
                    CreateOrUpdateActivity.jumpCreateOrUpdateActivity(this, model)
                } else if ("生成报表".equals(item, ignoreCase = true)) {
                    TotalConsumeReportActivity.start(this, model)
                } else if ("置顶".equals(item, ignoreCase = true)) {
                    mMainActivityViewModel.setTop(model)
                } else if ("移动".equals(item, ignoreCase = true)) {
                    mMainActivityViewModel.searchItemModelFromLongClick = model
                    SelectNodeActivity.start(this,searchItemModel = null, selectId = model.id, requestCode = SubItemActivity.REQUEST_CODE_SELECT_NODE)
                } else if ("取消置顶".equals(item, ignoreCase = true)) {
                    mMainActivityViewModel.setCancelTop(model)
                }
            }.show()
            true
        }
        binding?.searchBar?.setOnClickListener { SearchActivity.jumpSearchActivity(this@MainActivity) }
    }

    private fun checkManagerPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R ||
            Environment.isExternalStorageManager()) {
            if (checkSelfPermission(android.Manifest.permission.QUERY_ALL_PACKAGES) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(arrayOf(android.Manifest.permission.QUERY_ALL_PACKAGES), 0)
            }
        } else {
            val builder = AlertDialog.Builder(this)
                .setMessage("本程序需要您同意允许访问所有文件权限")
                .setPositiveButton("确定") { _, _ ->
                    val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
                    startActivity(intent)
                }
            builder.show()
        }
    }

    override fun onResume() {
        super.onResume()
        mMainActivityViewModel.loadData()
    }

    override fun handleRightButton(itemId: Int) {
        super.handleRightButton(itemId)
        when (itemId) {
            R.id.action_about -> {
                startActivity(Intent(this, AboutActivity::class.java))
            }
            R.id.action_add -> CreateOrUpdateActivity.jumpCreateOrUpdateActivity(this, null)
            R.id.action_sort -> SortItemActivity.jumpSortItemActivity(this, null)
        }
    }

    override val titleBarResId = R.id.toolbar
    override val menuResId = R.menu.home_menu

    override fun showBackButton() = false

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) return
        when (requestCode) {
            SubItemActivity.REQUEST_CODE_SELECT_NODE -> {
                val searchItemModel:SearchItemModel? = data?.getParcelableExtra("data")
                searchItemModel?.let {
                    mMainActivityViewModel.moveTo(it)
                    ToastUtils.show("已移动至\"${it.name}\"")
                }
            }
        }
    }
}